package com.gzc.just.play.last.war.robotclient.handler;

import com.gzc.just.play.last.war.common.annotation.MessageHandler;
import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.protobuf.ls.lstogc.LSToGC;
import com.gzc.just.play.last.war.robotclient.NettyRobotClient;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@MessageHandler(serverTypes = MessageHandler.ServerType.ROBOT_CLIENT)
public class LoginResponseHandler implements SimpleMessageHandler {
    private static final Logger log = LoggerFactory.getLogger(LoginResponseHandler.class);

    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        LSToGC.LoginResult loginResult = null;
        if (message instanceof byte[]) {
            loginResult = LSToGC.LoginResult.parseFrom((byte[]) message);
        } else if (message instanceof LSToGC.LoginResult) {
            loginResult = (LSToGC.LoginResult) message;
        }

        NettyRobotClient client = ctx.channel().attr(NettyRobotClient.CLIENT_KEY).get();
        if (client == null) {
            log.warn("LoginResponseHandler: Robot client not found in channel attributes");
            return;
        }

        if (loginResult != null) {
            log.info("Robot {} received login response: result={}", client.getRobotId(), loginResult.getResult());
            if (loginResult.getResult() >= 0) {
                log.info("Robot {} login success", client.getRobotId());
            } else {
                log.warn("Robot {} login failed", client.getRobotId());
            }
        }
    }

    @Override
    public int getMessageId() {
        return 512;
    }

    @Override
    public String getName() {
        return "LoginResponseHandler";
    }

    @Override
    public Logger getLogger() {
        return log;
    }
}
